package com.woniu.deal.order.controller;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.woniu.common.entity.DealOrder;
import com.woniu.common.entity.DealRechargeorder;
import com.woniu.common.entity.DealUseraccount;
import com.woniu.deal.order.configuration.AliPayConfig;
import com.woniu.deal.order.service.DealOrderService;
import com.woniu.deal.order.service.DealRechargeorderService;
import com.woniu.deal.order.service.DealUseraccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/alipay")
public class AliPayController {
    //支付宝沙箱网管地址
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    //签名方式
    private static final String SIGN_TYPE = "RSA2";

    @Resource
    private AliPayConfig aliPayConfig;

    @Autowired
    private DealOrderService dealOrderService;
    @Autowired
    private DealRechargeorderService dealRechargeorderService;
    @Autowired
    private DealUseraccountService dealUseraccountService;


    @GetMapping("/{dealOrderNum}")
    public String pay(@PathVariable("dealOrderNum") String dealOrderNum/*, HttpServletResponse response*/){
        //查询订单信息
        DealRechargeorder dealOrder = dealOrderService.selectByOrderNum(dealOrderNum);
        //创建client，通用SDK提供的client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL,aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(),FORMAT,CHARSET,aliPayConfig.getAlipayPublicKey(),SIGN_TYPE);
        //创建Request并设置request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); //发送请求的Request类
        request.setNotifyUrl(aliPayConfig.getNotifyUrl()); //回调函数的地址
        JSONObject bizContent = new JSONObject();
        bizContent.set("out_trade_no",dealOrder.getRechargeorderNo()); //自己生成的订单编号
        bizContent.set("total_amount",dealOrder.getRechargeorderTotal()); //订单的总金额
        bizContent.set("subject",dealOrder.getRechargeorderGoodsname()); //支付的名称
        bizContent.set("product_code","FAST_INSTANT_TRADE_PAY"); //固定配置
        request.setBizContent(bizContent.toString());
        request.setReturnUrl("http://localhost:5173/dealAccount"); //支付完成后自动跳转到本地页面的路径
        //执行请求，拿到响应的结果，返回给浏览器
        String form = "";

        try {
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return form;
    }

    @RequestMapping("/notify")
    @Transactional
    public void payNotify(HttpServletRequest request) throws Exception {
        if(request.getParameter("trade_status").equals("TRADE_SUCCESS")){
            System.out.println("=========支付宝异步回调=========");

            Map<String,String> params = new HashMap<>();
            Map<String,String[]> requestParams = request.getParameterMap();

            for(String name : requestParams.keySet()){
                params.put(name,request.getParameter(name));
            }

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content,sign,aliPayConfig.getAlipayPublicKey(),"UTF-8");
            //支付宝验签
            if(checkSignature){
                //验签通过
                String tradeNo = params.get("out_trade_no");
                System.out.println(tradeNo);
                DealRechargeorder dealRechargeorder = dealOrderService.selectByOrderNum(tradeNo);
                dealRechargeorder.setRechargeorderStatus("已支付");
                dealRechargeorderService.updateById(dealRechargeorder);
                DealUseraccount dealUseraccount = dealUseraccountService.getByUserId(dealRechargeorder.getUserId());
                dealUseraccount.setUseraccountBalance(dealUseraccount.getUseraccountBalance().
                        add(new BigDecimal(params.get("total_amount"))));
                dealUseraccountService.updateById(dealUseraccount);

            }


        }
    }
}
